//
//  BuyDetailViewController.m
//  午分享_WKWebView
//
//  Created by dllo on 16/1/19.
//  Copyright © 2016年 李贺. All rights reserved.
//

#import "BuyDetailViewController.h"
#import "BaseTableView.h"
#import "FindModel.h"
#import <UIImageView+WebCache.h>
#import "BaseLabel.h"
#import "LHAFNetworkTool.h"
#import "RepeatImageView.h"
#import "BaseView.h"
#import <MJRefresh.h>
#import "BaseButton.h"
#import "BrandDescTableViewCell.h"
#import "BrandActivityTableViewCell.h"
#import "CustomerServiceTableViewCell.h"
#import "BaseCollectionView.h"
#import "GoodsCollectionViewCell2.h"
#import <MBProgressHUD.h>
#import "DataBaseManager.h"
#import "ConstantsDefine.h"

@interface BuyDetailViewController ()<UITableViewDataSource, UITableViewDelegate, RepeatImageViewDelegate, UIWebViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UMSocialUIDelegate>

@property (nonatomic, retain) BaseTableView *tableView;
@property (nonatomic, retain) BaseLabel *goodsNameLabel; /**< 商品名 */
@property (nonatomic, retain) BaseLabel *promoteLabel; /**< 促销价 */
@property (nonatomic, retain) BaseLabel *marketLabel; /**< 定价 */
@property (nonatomic, retain) NSArray *keyArray;
@property (nonatomic, retain) NSDictionary *dataDic;
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, retain) BaseCollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, copy) NSString *str;
@property (nonatomic, retain) MBProgressHUD *HUD;
@property (nonatomic, retain) UIButton *addButton; /**< 购买按钮 */
@property (nonatomic, assign) BOOL judge; /**< 判断是否已经收藏 */

@end

@implementation BuyDetailViewController
- (void)dealloc
{
    [_tableView release];
    [_goodsNameLabel release];
    [_promoteLabel release];
    [_marketLabel release];
    [_keyArray release];
    [_dataDic release];
    [_webView release];
    [_collectionView release];
    [_dataArray release];
    [_str release];
    [_goods_id release];
    [_HUD release];
    [_model release];
    [super dealloc];
}

- (void)handleData {
    
    // 根据 goods_id.length 判断拼接模式
    if (self.goods_id.length != 0) {
         self.str = [NSString stringWithFormat:@"http://api.ujipin.com/v2/app/ios/phone/v3/goods/index?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314&idx=goods&goods_id=%@", self.goods_id];
    } else {
        self.str = [NSString stringWithFormat:@"http://api.ujipin.com/v2/app/ios/phone/v3/goods/index?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314&idx=goods&goods_id=%@", _model.goods_id];
    }
   
    NSMutableArray *imageArray = [NSMutableArray array];
    [LHAFNetworkTool getUrl:self.str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        
/****************************** 创建TableView的头部 ************************************/
        
        self.dataDic = resposeObject[@"data"];
        NSDictionary *dic = self.dataDic[@"color"];
        self.keyArray = [dic allKeys];
        [imageArray addObjectsFromArray:dic[[self.keyArray  firstObject]][@"img"]];
        BaseView *backView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 410 * HEIGHT)];
        self.tableView.tableHeaderView = backView;
        [backView release];
        
        RepeatImageView *repeat = [RepeatImageView RepeatImageViewWithFrame:CGRectMake(0, 0, backView.frame.size.width, 300 * HEIGHT) imageArray:imageArray];
        repeat.delegate = self;
        [backView addSubview:repeat];
        
        
        self.goodsNameLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(10 * WIDTH, 310 * HEIGHT, backView.frame.size.width - 20 * WIDTH, 50 * HEIGHT)];
        self.goodsNameLabel.numberOfLines = 2;
        NSString *site = _dataDic[@"site_url"];
        NSString *brand = _dataDic[@"brand_name"];
        NSString *goods = _dataDic[@"goods_name"];
        _goodsNameLabel.text = [NSString stringWithFormat:@"[%@][%@]%@", site, brand, goods];
        [backView addSubview:_goodsNameLabel];
        [_goodsNameLabel release];
        
        self.promoteLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(10 * WIDTH, 370 * HEIGHT, 60 * WIDTH, 30 * HEIGHT)];
        _promoteLabel.textColor = [UIColor redColor];
        //        _promoteLabel.backgroundColor = [UIColor yellowColor];
        _promoteLabel.font = [UIFont systemFontOfSize:20 * WIDTH];
        if (![[resposeObject[@"data"][@"promote_price"] stringValue] isEqualToString:@"0"]) {
            _promoteLabel.text = [NSString stringWithFormat:@"¥%@", [resposeObject[@"data"][@"promote_price"] stringValue]];
        } else {
            _promoteLabel.text = [NSString stringWithFormat:@"¥%@", [resposeObject[@"data"][@"shop_price"] stringValue]];
        }
        
        [backView addSubview:_promoteLabel];
        [_promoteLabel release];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(75 * WIDTH, 388 * HEIGHT, 47 * WIDTH, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        [backView addSubview:lineView];
        [lineView release];
        
        self.marketLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(75 * WIDTH, 375 * HEIGHT, 60 * WIDTH, 25 * HEIGHT)];
        _marketLabel.textColor = [UIColor grayColor];
        //        _marketLabel.backgroundColor = [UIColor greenColor];
        _marketLabel.text = [NSString stringWithFormat:@"¥%@", [resposeObject[@"data"][@"market_price"] stringValue]];
        [backView addSubview:_marketLabel];
        [_marketLabel release];
        
        /***** 创建标题  *****/
        self.navigationItem.title = _dataDic[@"goods_name"];
    
        
/****************************** 创建cell中的webView *************************************/
        
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
        _webView.delegate = self;
        _webView.scrollView.scrollEnabled = NO;
        //预先加载url
         NSString *strUrl = self.dataDic[@"IOS_url"];
        [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strUrl]]];
        
         FindModel *model = [FindModel modelWithDic:self.dataDic];
        self.judge = [[DataBaseManager shareInstance] selectDataWithgoods_id:model.goods_id];
        self.addButton.selected = self.judge;
        NSLog(@"ifReadOnly value: %@" ,self.judge?@"YES":@"NO");
        
        [self createTableFootView];
        [self createCollectionView];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.HUD hide:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"解析失败：%@", error);
    }];
}

// 加载视图
- (void)handleHUD {
    // 1. 创建对象
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    // 2. 添加到当前视图中
    [self.view addSubview:self.HUD];
    // 如果设置此属性, 则置后当前的View
    self.HUD.dimBackground = NO;
    // 设置模式
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    self.HUD.color = [UIColor colorWithWhite:0.800 alpha:1.000];
    [self.HUD show:YES];
}

#pragma mark - 创建tableFooterView
- (void)createTableFootView {
    NSString *str = [NSString stringWithFormat:@"http://api.ujipin.com/v2/app/ios/phone/v3/category/getListDataByCatId?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314&cid=%@", _dataDic[@"cat_id"]];
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"goods_list"];
        self.dataArray = [FindModel modelHandleWithArray:array];
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败:%@", error);
    }];
}

// 创建tableFooterView 上的collectionView
- (void)createCollectionView {
    
    BaseView *backView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 230 * HEIGHT)];
    backView.backgroundColor = [UIColor colorWithWhite:0.950 alpha:1.000];
    self.tableView.tableFooterView = backView;
    [backView release];
    
    BaseLabel *alabel = [[BaseLabel alloc] initWithFrame:CGRectMake(10 * WIDTH, 0, 100 * WIDTH, 20 * HEIGHT)];
    alabel.text = @"你可能喜欢";
    alabel.font = [UIFont systemFontOfSize:15 * WIDTH];
    [backView addSubview:alabel];
    [alabel release];
    
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    layout.itemSize = CGSizeMake(130 * WIDTH, 170 * HEIGHT);
    layout.minimumInteritemSpacing = 10 * WIDTH;
    layout.minimumLineSpacing = 10 * HEIGHT;
    layout.sectionInset = UIEdgeInsetsMake(0, 5 * WIDTH, 0, 5 * WIDTH);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 30 * HEIGHT, self.view.frame.size.width, 170 * HEIGHT) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor colorWithWhite:0.950 alpha:1.000];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    //        self.collectionView.bounces = NO;
    [backView addSubview:_collectionView];
    [_collectionView release];
    [_collectionView registerClass:[GoodsCollectionViewCell2 class] forCellWithReuseIdentifier:@"Goods"];
}

// collectionViewcell 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArray.count;
}

// collectionViewcell设置
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 获取cell
    GoodsCollectionViewCell2 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Goods" forIndexPath:indexPath];
    FindModel *model = _dataArray[indexPath.item];
    cell.model = model;
//        cell.backgroundColor = [UIColor redColor];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%@", indexPath);
    BuyDetailViewController *buy = [[BuyDetailViewController alloc] init];
    FindModel *model = _dataArray[indexPath.item];
    buy.model = model;
    [self.navigationController pushViewController:buy animated:YES];
}


// 下拉刷新
- (void)addHeaderRefresh {
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self handleData];
    }];
    // 设置普通状态的动画图片
    NSArray *idleImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态
    NSArray *pullingImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSInteger i = 0; i < 24; i++) {
        [refreshingImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%ld", i]]];
    }
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置所有数据加载完毕的动画图片
    NSArray *NoMoreDataImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:NoMoreDataImages forState:MJRefreshStateNoMoreData];
    
    self.tableView.mj_header = header;
    
    // 隐藏时间-
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 隐藏状态
    header.stateLabel.hidden = YES;
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - UIWebView Delegate Methods
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //获取到webview的高度
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webView.frame = CGRectMake(0,0, self.view.frame.size.width, height * HEIGHT);
    [self.tableView reloadData];
}

- (void)didClickImage:(NSInteger)tag {
    NSLog(@"%ld", tag);
}

- (void)createTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 50 * HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[BrandDescTableViewCell class] forCellReuseIdentifier:@"cell1"];
    [_tableView registerClass:[BrandActivityTableViewCell class] forCellReuseIdentifier:@"cell2"];
    [_tableView registerClass:[CustomerServiceTableViewCell class] forCellReuseIdentifier:@"cell3"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.dataDic[@"color"][[self.keyArray firstObject]];
    
    if (indexPath.row == 0) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"size"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"size"];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"颜色:%@ 尺码:%@", dic[@"color_name"], [dic[@"sku"] firstObject][@"size"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
        return cell;
        
    } else if (indexPath.row == 1) {
        
        BrandDescTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        [cell.logoImageView sd_setImageWithURL:[NSURL URLWithString:_dataDic[@"app_show_logo"]] placeholderImage:[UIImage imageNamed:@"place2"]];
        cell.brandLabel.text = _dataDic[@"brand_name"];
        cell.siteLabel.text = _dataDic[@"site_url"];
        cell.descLabel.text = _dataDic[@"brand_app_desc"];
        return cell;
        
    } else if (indexPath.row == 2) {
        
        NSArray *array = self.dataDic[@"IOS_activeStr"];
        BrandActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        NSString *activeStr = @"";
        for (NSString *str in array) {
            activeStr = [activeStr stringByAppendingFormat:@"\n%@", str];
           
        }
        cell.alabel.text = activeStr;
        return cell;
        
    } else if (indexPath.row == 3) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"web"];
        if (!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"web"];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        [cell.contentView addSubview:self.webView];
        
        return cell;
        
    } else if (indexPath.row == 4) {
        
        CustomerServiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        return cell;
        
    } else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 根据row逐个判断高度
    if (indexPath.row == 0) {
        
        return 50 * HEIGHT;
        
    } else if (indexPath.row == 1) {
        
        CGFloat h = [BrandDescTableViewCell heightWithText:self.dataDic[@"brand_app_desc"]];
        return h * HEIGHT + 140 * HEIGHT;
        
    } else if (indexPath.row == 2) {
        
        NSArray *array = _dataDic[@"IOS_activeStr"];
        NSString *activeStr = @"";
        for (NSString *str in array) {
            activeStr = [str stringByAppendingFormat:@"\n%@", str];
        }
        CGFloat h = [BrandActivityTableViewCell heightWithText:activeStr];
        return h * HEIGHT + 40 * HEIGHT;
        
    } else if (indexPath.row == 3) {
        
        return _webView.frame.size.height;
        
    } else if (indexPath.row == 4) {
        return 180 * HEIGHT;
    }
    else {
        return 50 * HEIGHT;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10 * HEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10 * HEIGHT;
}

- (void)setModel:(FindModel *)model {
    if (_model != model) {
        [_model release];
        _model = [model retain];
    }
    [self handleData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createTableView];
    [self addHeaderRefresh];
    [self handleHUD];
    BaseView *bottomView = [[BaseView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50 * HEIGHT, self.view.frame.size.width, 50 * HEIGHT)];
    bottomView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:bottomView];
    [bottomView release];
    
    BaseButton *praiseButton = [BaseButton buttonWithType:UIButtonTypeCustom];
    praiseButton.frame = CGRectMake(0, 0, bottomView.frame.size.width / 5, 50 * HEIGHT);
    [praiseButton setImage:[UIImage imageNamed:@"iconfont-xin-8"] forState:UIControlStateNormal];
    [praiseButton setImage:[UIImage imageNamed:@"iconfont-xin-9"] forState:UIControlStateSelected];
    [bottomView addSubview:praiseButton];
    
    BaseButton *bagButton = [BaseButton buttonWithType:UIButtonTypeCustom];
    bagButton.frame = CGRectMake(bottomView.frame.size.width / 5 + 1, 0, bottomView.frame.size.width / 5 - 1, 50 * HEIGHT);
    [bagButton setImage:[UIImage imageNamed:@"iconfont-gouwu-4"] forState:UIControlStateNormal];
    [bottomView addSubview:bagButton];
    
    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _addButton.frame = CGRectMake(bottomView.frame.size.width / 5 * 2, 0, bottomView.frame.size.width / 5 * 3, 50 * HEIGHT);
    _addButton.backgroundColor = [UIColor colorWithRed:1.000 green:0.000 blue:0.000 alpha:0.600];
    [_addButton setTitle:@"加入购物袋" forState:UIControlStateNormal];
    [_addButton setTitle:@"已购买" forState:UIControlStateSelected];
    _addButton.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTH];
    [bottomView addSubview:_addButton];
    [_addButton addTarget:self action:@selector(handleShopping:) forControlEvents:UIControlEventTouchUpInside];
    [[DataBaseManager shareInstance] openDB];
    [[DataBaseManager shareInstance] createTable];
    NSLog(@"%@", NSHomeDirectory());
   
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(handleShare:)];
}

- (void)handleShare:(UIBarButtonItem *)rightBar {
    /* 分享 */
    FindModel *model = [FindModel modelWithDic:self.dataDic];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:UM shareText:model.goods_name shareImage:model.app_show_logo shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, UMShareToTencent, UMShareToQzone, UMShareToWechatTimeline, nil] delegate:self];
}

- (void)handleShopping:(UIButton *)button {
    button.selected = !button.selected;
    FindModel *model = [FindModel modelWithDic:self.dataDic];
    if (button.selected == YES) {
        [[DataBaseManager shareInstance] insertFindModel:model];
        NSLog(@"%@ %@ %@ %@",model.goods_id, model.goods_name, model.app_show_logo, model.shop_price);
    } else {
        [[DataBaseManager shareInstance] deleteFindModelWithId:model.goods_id];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [[DataBaseManager shareInstance] closeDB];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
